﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;

namespace Ams.Mvc.Bootstrap
{
    public static class HtmlMod
    {
        public static void AddClass(ref string html, string @class)
        {
            AppendToAttributeValue(ref html, "class", @class.Split(new[] { " " }, StringSplitOptions.RemoveEmptyEntries));
        }

        public static void AppendToAttributeValue(ref string html, string attribtue, IEnumerable<string> valuesToAdd)
        {
            //Define the pattern
            var regexMatchPattern = String.Format("(?<={0}=\")[^\"]+(?=\")", attribtue);

            //Find the current value
            var captures = Regex.Match(html, regexMatchPattern).Captures;
            if (captures.Count == 0) return;

            var attributeValue = captures[0].Value;

            //Convert the current values to a list
            var values = attributeValue.Split(new[] { " " }, StringSplitOptions.RemoveEmptyEntries).ToList();

            //Add the new values
            values.AddRange(valuesToAdd);

            //Convert the list back to a string
            var valueString = String.Join(" ", values.Distinct(StringComparer.InvariantCultureIgnoreCase));

            //Set the new value
            html = Regex.Replace(html, regexMatchPattern, valueString);
        }

        public static void AppendToAttributeList(ref IDictionary<string, object> htmlAttributes, string attributeName,string attributeValue)
        {
            if (htmlAttributes.ContainsKey(attributeName))
            {
                htmlAttributes[attributeName] = ((htmlAttributes[attributeName] ?? String.Empty) + " " + attributeValue).Trim();
            }
            else
            {
                htmlAttributes.Add(attributeName, attributeValue);
            }
        }
    }
}
